import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/reports.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/class/ClassDetails.dart';
import 'package:ichinesereader/models/student/assignmentSearchDto.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/pages/common/report/classReportBottom.dart';
import 'package:ichinesereader/pages/common/report/classReportOverallData.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/sidebars/adminReportSidebar.dart';
import 'package:sidebarx/sidebarx.dart';

class SchoolAdminReportsClass extends StatefulWidget {
  SchoolAdminReportsClass({Key? key}) : super(key: key);
  static const String routeName = '/schooladmin/reports/class';

  @override
  _SchoolAdminReportsClass createState() => _SchoolAdminReportsClass();
}

class _SchoolAdminReportsClass extends State<SchoolAdminReportsClass> {
  final ReportsController _reportsController = Get.find();
  final SchoolAdminController _schoolAdminController = Get.find();
  var box = Hive.box('appconfig');

  bool isSchoolAdmin = false;
  var selectedTime = Constants.timeRanges[0];
  var selectedClass;
  var startTime;
  var endTime;
  bool isFirstAttemp = false;

  // @pragma('vm:entry-point')
  // static void downloadCallback(
  //     String id, DownloadTaskStatus status, int progress) {
  //   final SendPort send =
  //       IsolateNameServer.lookupPortByName('downloader_send_port')!;
  //   send.send([id, status, progress]);
  // }

  @override
  void initState() {
    isSchoolAdmin = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin;
    if ((GetPlatform.isAndroid || GetPlatform.isIOS) && !GetPlatform.isWeb) {
      // FlutterDownloader.registerCallback(downloadCallback);
    }

    if (isSchoolAdmin) {
      if (_schoolAdminController.classItems.isEmpty) {
        _schoolAdminController.fetchSchoolAllClassesDetailsWithoutAll();
      }
      Future.delayed(Duration(milliseconds: 1200), () {
        if (_schoolAdminController.classItems.isNotEmpty) {
          var temp;
          if (_schoolAdminController.classItems.length > 1) {
            temp = _schoolAdminController.classItems[1];
          } else {
            temp = _schoolAdminController.classItems[0];
          }
          fetchOverallData(temp, startTime, endTime);
          fetchChartData(temp);

          setState(() {
            selectedClass = temp as ClassDetails;
          });
        }
      });
    }
    super.initState();
  }

  void fetchOverallData(ClassDetails sClass, startTime, endTime) {
    if (sClass.classId != null) {
      var classId = sClass.classId;
      if (sClass.classId == "All") {
        classId = "AllClass";
      }
      _reportsController.fetchClassOverviewTotalData(
          classId!, startTime, endTime);
    }
  }

  void fetchChartData(ClassDetails sClass) {
    if (sClass.classId != "All") {
      _reportsController.fetchClassProficiencyLevelData(sClass.classId!);
      _reportsController.fetchClassSkillsData(sClass.classId!, false);
      AssignmentSearchDto dto = new AssignmentSearchDto(
          assignmentType: "ASSIGNMENT",
          live: true,
          past: false,
          sortField: "-created");
      _reportsController.fetchClassAssignmentsData(sClass.classId!, dto);
    }
  }

  void _downloadAllReport() async {
    //String dir = (await getApplicationDocumentsDirectory()).path;
    try {
      _reportsController.downloadAllClassReport();
      Future.delayed(Duration(milliseconds: 3000), (() async {
        launchInWebViewWithJavaScript(
            _reportsController.allClassReport.value.result!.fileLink!);

        // if ((GetPlatform.isAndroid || GetPlatform.isIOS) &&
        //     !GetPlatform.isWeb) {
        //   await FlutterDownloader.enqueue(
        //     url: _reportsController
        //         .allClassReport.value.result!.fileLink!, // file url
        //     savedDir: '$dir/',
        //     fileName: 'allclassReports',
        //     saveInPublicStorage: true,
        //   );
        // } else {
        //   launchInWebViewWithJavaScript(
        //       _reportsController.allClassReport.value.result!.fileLink!);
        // }

        print("Download successfully");
      }));
    } catch (e) {
      print("eerror :::: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build SchoolAdminReportsClass');
    // final isSmallScreen =
    //     MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.schoolAdminPageItems
        .indexWhere((page) => page.route == Get.currentRoute);
    final SidebarXController _xController = SidebarXController(
        selectedIndex: _selectedSidebarItem, extended: isBigScreen);
    final PageStyles _pageStyles = PageStyles();

    return Container(
      decoration: _pageStyles.pageBoxDecoration(),
      child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: CustomAppBar(title: 'Class Reports'.tr),
          body: Container(
            child: Row(
              children: [
                Visibility(
                    visible: false,
                    child: AdminReportSidebarX(controller: _xController)),
                Expanded(
                  child: isSchoolAdmin
                      ? SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          padding: const EdgeInsets.all(8.0),
                          child: Center(
                            child: Padding(
                              padding: const EdgeInsets.all(10.0),
                              child: Column(
                                children: [
                                  DropdownButton(
                                    icon: Icon(
                                      Icons.arrow_drop_down_outlined,
                                      color: Colors.blue[300],
                                    ),
                                    hint: Text('Choose Class'.tr),
                                    value: selectedClass,
                                    items: _schoolAdminController.classItems
                                        .map((selectedClass) {
                                      return DropdownMenuItem(
                                        value: selectedClass,
                                        child: Text(
                                          selectedClass.className.toString(),
                                          style: Theme.of(context)
                                              .textTheme
                                              .titleSmall,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      );
                                    }).toList(),
                                    onChanged: (value) {
                                      value as ClassDetails;
                                      setState(() {
                                        selectedClass = value;
                                        selectedTime = Constants.timeRanges[0];
                                        startTime = null;
                                        endTime = null;
                                      });
                                      fetchOverallData(
                                          value, startTime, endTime);
                                      fetchChartData(value);
                                    },
                                  ),
                                  Obx(() => ClassReportOverallData(
                                        selectedTime: selectedTime,
                                        updateSelectedTime: (arg) {
                                          setState(() {
                                            selectedTime = arg;
                                          });
                                        },
                                        startTime: startTime,
                                        endTime: endTime,
                                        updateCustomTime: (arg1, arg2) {
                                          setState(() {
                                            startTime = arg1;
                                            endTime = arg2;
                                          });
                                          fetchOverallData(
                                              selectedClass, arg1, arg2);
                                        },
                                        classOverviewTotalData:
                                            _reportsController
                                                .classoverviewtotal.value,
                                      )),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  selectedClass != null
                                      ? selectedClass.classId == "All"
                                          ? Container(
                                              child: ElevatedButton(
                                              child: Text(
                                                  "Download Report of All Classes"),
                                              onPressed: _downloadAllReport,
                                            ))
                                          : ClassReportBottom()
                                      : Text("")
                                ],
                              ),
                            ),
                          ),
                        )
                      : Text(''),
                )
              ],
            ),
          )),
    );
  }
}
